/*
 *  Copyright (c) 2013 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.cloopen.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
package com.yuntongxun.ecdemo.ui.chatting.model;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;

import com.squareup.picasso.Picasso;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.chatting.ChattingActivity;
import com.yuntongxun.ecdemo.ui.chatting.holder.BaseHolder;
import com.yuntongxun.ecdemo.ui.chatting.holder.DescriptionViewHolder;
import com.yuntongxun.ecdemo.ui.chatting.view.CCPChattingFooter2;
import com.yuntongxun.ecdemo.ui.chatting.view.ChattingItemContainer;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.voicechat.bean.PostResult;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.comman.EventBusTags;
import com.yuntongxun.ecdemo.voicechat.comman.GiftContacts;
import com.yuntongxun.ecdemo.voicechat.comman.TopicContacts;
import com.yuntongxun.ecdemo.voicechat.view.MyImageSpan;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.im.ECTextMessageBody;
import com.yuntongxun.ecsdk.im.ECCallMessageBody;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import de.greenrobot.event.EventBus;


/**
 * <p>Title: DescriptionRxRow.java</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Company: Beijing Speedtong Information Technology Co.,Ltd</p>
 * @author Jorstin Chan
 * @date 2014-4-17
 * @version 1.0
 */
public class DescriptionRxRow extends BaseChattingRow {

	
	public DescriptionRxRow(int type){
		super(type);
	}
	@Override
	public View buildChatView(LayoutInflater inflater, View convertView) {
        //we have a don't have a converView so we'll have to create a new one
        if (convertView == null ) {
            convertView = new ChattingItemContainer(inflater, R.layout.chatting_item_from);

            //use the view holder pattern to save of already looked up subviews
            DescriptionViewHolder holder = new DescriptionViewHolder(mRowType);
            convertView.setTag(holder.initBaseHolder(convertView, true));
        } 
		return convertView;
	}

	@Override
	public void buildChattingData(final Context context, BaseHolder baseHolder,
			ECMessage detail, int position) {

		DescriptionViewHolder holder = (DescriptionViewHolder) baseHolder;
		ECMessage message = detail;
		if(message != null) {
			if (message.getType() == ECMessage.Type.TXT) {
				String msgType="";
				JSONArray jsonArray=null;
				if (!TextUtils.isEmpty(message.getUserData())) try {
					JSONObject jsonObject = new JSONObject(message.getUserData());
					msgType = jsonObject.getString(CCPChattingFooter2.TXT_MSGTYPE);
					jsonArray = jsonObject.getJSONArray(CCPChattingFooter2.MSG_DATA);

				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (TextUtils.equals(msgType, CCPChattingFooter2.FACETYPE)) {
					holder.getDescTextView().setBackgroundResource(0);
				} else {
					holder.getDescTextView().setBackgroundResource(R.drawable.chat_from_bg_normal);
				}
				ECTextMessageBody textBody = (ECTextMessageBody) message.getBody();
				String msgTextString =textBody.getMessage();
				Log.e("msgrx",msgTextString);
				if (msgTextString.startsWith("[gift]")){
					holder.getBaseLayout().setVisibility(View.VISIBLE);
					holder.getClickAreaView().setVisibility(View.VISIBLE);
					holder.getDescTextView().setVisibility(View.GONE);
					holder.getTopicLayout().setVisibility(View.GONE);

					View.OnClickListener onClickListener = ((ChattingActivity) context).mChattingFragment.getChattingAdapter().getOnClickListener();
					ViewHolderTag holderTag = ViewHolderTag.createTag(message,
							ViewHolderTag.TagType.TAG_GIFT, position);
					holder.getClickAreaView().setTag(holderTag);
					holder.getClickAreaView().setOnClickListener(onClickListener);
				}else if(msgTextString.startsWith("[conf]")){
					holder.getBaseLayout().setVisibility(View.VISIBLE);
					String confInfo= message.getUserData();
					Log.e("confInfoRx",confInfo);
					holder.getClickAreaView().setVisibility(View.GONE);
					holder.getDescTextView().setVisibility(View.VISIBLE);
					holder.getTopicLayout().setVisibility(View.GONE);
					holder.getDescTextView().setText(msgTextString);

					String meetingNo="";
					try {
						JSONObject object = new JSONObject(confInfo);
						meetingNo=object.optString("confId");
						PostResult postResult = new PostResult();
						postResult.setTag(EventBusTags.MEETING_NO);
						postResult.setResult(meetingNo);
						EventBus.getDefault().post(postResult);

					}catch (Exception e){
						LogUtil.e("roomNo",e.toString());
					}

					if (!TextUtils.isEmpty(meetingNo)){
						holder.getDescTextView().setText("Start a group chat");
					}else{
						holder.getDescTextView().setText("Exit group chat");
					}

				}else if((msgTextString.startsWith("[topic]"))) {
					holder.getBaseLayout().setVisibility(View.VISIBLE);
					holder.getClickAreaView().setVisibility(View.GONE);
					holder.getTopicLayout().setVisibility(View.VISIBLE);
					holder.getDescTextView().setVisibility(View.GONE);
					String question="",answer="";
					int type=0; //0=文本、1=语音
					String topicInfo= message.getUserData();
					try {
						JSONObject object=new JSONObject(topicInfo);
						question=object.optString("question");
						answer=object.optString("answer");
						type=object.getInt("type");
						if (type==1){
							holder.getQuestionTv().setVisibility(View.GONE);
							holder.getAnswerTv().setVisibility(View.GONE);
							holder.getQuestionBtn().setVisibility(View.VISIBLE);
							if (answer.toString().trim().equals("")){
								holder.getAnswerBtn().setVisibility(View.GONE);
							}else{
								holder.getAnswerBtn().setVisibility(View.VISIBLE);
							}
						}else{
							holder.getQuestionTv().setVisibility(View.VISIBLE);
							holder.getQuestionTv().setText(question);
							holder.getAnswerTv().setVisibility(View.VISIBLE);
							holder.getAnswerTv().setText(answer);
							holder.getQuestionBtn().setVisibility(View.GONE);
							holder.getAnswerBtn().setVisibility(View.GONE);
						}
						View.OnClickListener onClickListener = ((ChattingActivity) context).mChattingFragment.getChattingAdapter().getOnClickListener();
						ViewHolderTag holderTag = ViewHolderTag.createTag(message,
								ViewHolderTag.TagType.TAG_TOPIC_QUESTION, position);
						holder.getQuestionBtn().setTag(holderTag);
						holder.getQuestionBtn().setOnClickListener(onClickListener);

						ViewHolderTag holderTag1 = ViewHolderTag.createTag(message,
								ViewHolderTag.TagType.TAG_TOPIC_ANSWER, position);
						holder.getAnswerBtn().setTag(holderTag1);
						holder.getAnswerBtn().setOnClickListener(onClickListener);

						ECContacts contact = ContactSqlManager.getContact(detail.getForm());
						String info=contact.getNickname();
//						MyImageSpan nativeSpan = new MyImageSpan(mContext, R.drawable.ic_speak);
//						MyImageSpan learnSpan = new MyImageSpan(mContext, R.drawable.ic_learn);
						if (info.contains("(")) {
							int index = info.indexOf("(");
							String infomation=info.substring(index+1,info.length()-1);
//                    String[] infos=infomation.split("-");
							UserInfo infos=null;
							try {
								infos=parseResult(infomation);
							} catch (Exception e) {
								e.printStackTrace();
							}

							if (infos!=null){
								holder.infoTv.setText(infos.getNickName());
								String name = infos.getNickName()+"  ";
								String age = "  "+infos.getAge()+"  ";
								String nativel = " ";
								String learn = " ";
								if (infos.getNativeLanguage()!=null){
									nativel="  "+infos.getNativeLanguage()+"  ";
								}
								if (infos.getLearningLanguage()!=null){
									learn="  "+infos.getLearningLanguage()+"";
								}
//
//
								if (infos.getGender().equals("男")){
									genderSpan = new MyImageSpan(mContext, R.drawable.ic_man);
								}else{
									genderSpan = new MyImageSpan(mContext, R.drawable.ic_woman);
								}

//								nativeSpan = new MyImageSpan(mContext, R.drawable.ic_speak);
//								learnSpan = new MyImageSpan(mContext, R.drawable.ic_learn);

								try {
									InputStream is = mContext.getAssets().open("flag/"+infos.getCountry()+".png");
									flagSpan = new MyImageSpan(mContext, BitmapFactory.decodeStream(is));
									is.close();
								} catch (IOException e) {
									Log.e("----",e.toString());
								}

								holder.infoTv.setText("");
								//姓名
								SpannableString nameShow = new SpannableString(name);
								ForegroundColorSpan blackSpan = new ForegroundColorSpan(Color.BLACK);
								nameShow.setSpan(blackSpan,0,name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
								holder.infoTv.append(nameShow);

								//插入性别图标
								SpannableString showString = new SpannableString("1");
								showString.setSpan(genderSpan,0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
								holder.infoTv.append(showString);

								//年龄颜色
								SpannableString ageShow = new SpannableString(age);
								ForegroundColorSpan yellowSpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.voice_yellow));
								ageShow.setSpan(yellowSpan,0,age.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
								holder.infoTv.append(ageShow);

								//插入国旗图标
								showString.setSpan(flagSpan, 0, 1 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
								holder.infoTv.append(showString);

								holder.infoTv.append("  ");

//								//插入本地语言的图标
//								showString.setSpan(nativeSpan, 0, 1 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//								holder.infoTv.append(showString);
//
//								//本地语言颜色
//								SpannableString nativeShow = new SpannableString(nativel);
//								ForegroundColorSpan greenSpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.voice_green));
//								nativeShow.setSpan(greenSpan,0,nativel.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//								holder.infoTv.append(nativeShow);
//
//								//插入学习的图标
//								showString.setSpan(learnSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//								holder.infoTv.append(showString);
//
//								//学习语言颜色
//								SpannableString learnShow = new SpannableString(learn);
//								ForegroundColorSpan greenSpan1 = new ForegroundColorSpan(mContext.getResources().getColor(R.color.voice_green));
//								learnShow.setSpan(greenSpan1,0,learn.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//								holder.infoTv.append(learnShow);



							}
						}else {
							holder.getBaseLayout().setVisibility(View.VISIBLE);
							holder.getNameTv().setText(detail.getForm());
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}


				}else {
					holder.getBaseLayout().setVisibility(View.VISIBLE);
					holder.getClickAreaView().setVisibility(View.GONE);
					holder.getDescTextView().setVisibility(View.VISIBLE);
					holder.getTopicLayout().setVisibility(View.GONE);
					holder.getDescTextView().showMessage(message.getId() + "", msgTextString, msgType, jsonArray);
					holder.getDescTextView().setMovementMethod(LinkMovementMethod.getInstance());
					View.OnClickListener onClickListener = ((ChattingActivity) context).mChattingFragment.getChattingAdapter().getOnClickListener();
					ViewHolderTag holderTag = ViewHolderTag.createTag(message,
							ViewHolderTag.TagType.TAG_IM_TEXT, position);
					holder.getDescTextView().setTag(holderTag);
					holder.getDescTextView().setOnClickListener(onClickListener);
				}
			} else if (message.getType() == ECMessage.Type.CALL) {
				holder.getBaseLayout().setVisibility(View.VISIBLE);
				ECCallMessageBody textBody = (ECCallMessageBody) message.getBody();
				holder.getDescTextView().setText(textBody.getCallText());
				holder.getDescTextView().setMovementMethod(LinkMovementMethod.getInstance());
			}
		}
	}

	@Override
	public int getChatViewType() {

		return ChattingRowType.DESCRIPTION_ROW_RECEIVED.ordinal();
	}

	@Override
	public boolean onCreateRowContextMenu(ContextMenu contextMenu,
			View targetView, ECMessage detail) {

		return false;
	}
}
